using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using TianShu.Domain.Entities;

namespace TianShu.Domain.Repositories
{
    public abstract class RepositoryRegistrarBase
    {
        public IServiceCollection Services { get; set; }

        protected RepositoryRegistrarBase(IServiceCollection services)
        {
            Services = services;
        }

        public virtual void AddRepositories()
        {
            RegisterDefaultRepositories();
        }


        protected virtual void RegisterDefaultRepositories()
        {
            foreach (var entityType in GetEntityTypes())
            {
                if (!ShouldRegisterDefaultRepositoryFor(entityType))
                {
                    continue;
                }

                RegisterDefaultRepository(entityType);
            }
        }


        protected virtual void RegisterDefaultRepository(Type entityType)
        {
            Services.AddDefaultRepository(
                entityType,
                GetDefaultRepositoryImplementationType(entityType)
            );
        }

        protected virtual Type GetDefaultRepositoryImplementationType(Type entityType)
        {
            var primaryKeyType = EntityHelper.FindPrimaryKeyType(entityType);

            if (primaryKeyType == null)
            {
                return GetRepositoryType(entityType);
            }

            return GetRepositoryType(entityType, primaryKeyType);
        }

        protected virtual bool ShouldRegisterDefaultRepositoryFor(Type entityType)
        {

            if (!typeof(IEntity).IsAssignableFrom(entityType))
            {
                return false;
            }

            return true;
        }

        protected abstract IEnumerable<Type> GetEntityTypes();

        protected abstract Type GetRepositoryType(Type entityType);

        protected abstract Type GetRepositoryType(Type entityType, Type primaryKeyType);
    }
}
